module("ufe.util.tair",package.seeall)
local http = require("ufe.resty.http")
local conf = require("ufe.config")

local ns = conf.tair_ns
local default_group = conf.tair_default_group
local groups = conf.tair_groups

local TAIR_URL = conf.tair_url or "http://127.0.0.1/tair_restful"
local TAIR_CONN_TIMEOUT = conf.tair_conn_timeout or 200
local TAIR_SEND_TIMEOUT = conf.tair_send_timeout or 200
local TAIR_RESP_TIMEOUT = conf.tair_resp_timeout or 200

function get(key, acf)
    local group
    if not acf or not acf.tair then
        group = default_group
    else
        group = acf.tair
    end

    local url = string.format("%s?group=%s&ns=%s&key=%s",TAIR_URL,group,ns,key)
    local hc = http:new()
    local ok, code, headers, status, body = hc:request{url = url,
        conn_timeout = TAIR_CONN_TIMEOUT,
        send_timeout = TAIR_SEND_TIMEOUT,
        resp_timeout = TAIR_RESP_TIMEOUT,
        method = "GET",
        headers = {
            ["Host"] = "tair.taobao.org",
            ["Connection"] = "close",
        },

    }
    if ok and code == 200 and body then
        return body
    else
        ngx.log(ngx.INFO, string.format("[UFE] can't get %s from tair", key))
        return nil
    end
end

function check_config()
    ns = tonumber(ns)
    if not ns then
        return false, "must set tair namespace in config.lua"
    end
    if not groups then
        return false, "must set tair group in config.lua"
    end
    if not default_group then
        return false, "must set default tair server in config.lua"
    end
    return true
end

function check(acf)
    local exist = false
    for _, g in ipairs(groups) do
        if g == acf.tair then
            exist = true
            break
        end
    end
    if not exist then
        return false, "not found or wrong tair"
    end
    return true
end
